import pandas as pd
import re


def find_all(sub, s):
    index_list = []
    index = s.find(sub)
    while index != -1:
        index_list.append(index)
        index = s.find(sub, index + 1)

    if len(index_list) > 0:
        return index_list
    else:
        return -1


def findSequence(allsequence: str, findsequences: str, windows: int = 15, site: int = 0) -> str:
    '''
    获得序列框内序列
    :param allsequence: string  完整序列
    :param findsequences: string 需要比对序列
    :param windows:  int  序列框大小，算一半，默认为15
    :param site: int 位置，默认为0
    :return: string 序列
    '''
    temp = findsequences
    if findsequences.startswith('-'):
        temp = findsequences.replace('-', '')
    if findsequences.endswith('-'):
        temp = findsequences.replace('-', '')

    # print(re.search(temp,allsequence).span())
    sequenceFirst, sequenceLast = re.search(temp, allsequence).span()
    acetyleFirst = 15
    ksite = findsequences[15]
    if ksite != 'K':
        acetyleFirst = 14
        ksite = findsequences[14]
        if ksite != 'K':
            acetyleFirst = 13
            ksite = findsequences[13]
            if ksite != 'K':
                acetyleFirst = 12
                ksite = findsequences[12]

    #
    # 阅读框的起位置
    windowsFirst = sequenceFirst + acetyleFirst - windows
    # 阅读框的结尾位置
    windowsLast = sequenceFirst + acetyleFirst + windows + 1
    # 拼接为数据
    if windowsFirst < 0:
        windowsdata = allsequence[0:windowsLast]
    else:
        windowsdata = allsequence[windowsFirst:windowsLast]
    # print(windowsdata)
    windowsdata = windowsdata.replace('\n', '')
    # 两端补齐
    if windowsFirst < 0:
        windowsdata = '-' * abs(windowsFirst) + windowsdata
    if len(allsequence) - windowsLast -1 < 0:
        windowsdata = windowsdata + '-' * abs(len(allsequence) - windowsLast -1)
    # print(windowsdata)
    # windowsdata=windowsdata.ljust(windows*2+1,'-')
    return windowsdata


sequence = {}
temp = 0
for i in open('sumclean.fasta'):
    if i.startswith('>'):
        z, uniport = i.split('|')
        temp = uniport[:-1]
    else:
        sequence[temp] = i

def makewindows(filename,windows=15):
    file = open(filename,'w')
    totalsum = {}
    for j in open('totalsum.csv'):
        x = j.split(',')
        if sequence[x[2]]:
            newsys = findSequence(sequence[x[2]], x[5].replace('\n', ''), windows, 0)
            file.write(x[0] + ',' + x[1] + ',' + x[2] + ',' + '{:.2f}'.format(float(x[3])) + ',' + x[
                4] + ',' + newsys + ',' + '{:.2f}'.format(float(x[6]))+"\n")
            print(x[0] + ',' + x[1] + ',' + x[2] + ',' + '{:.2f}'.format(float(x[3])) + ',' + x[
                4] + ',' + newsys + ',' + '{:.2f}'.format(float(x[6])), end='\n')
    file.close()

for i in range(15,35):
    makewindows("totalsum"+str(i)+".csv",i)